<?php
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Redis;
use App\OrderRecord;
use App\DeliveryRecord;
use App\Api\Controllers\BaseController;

class beforeOrder extends BaseController
{
  /**
   *@author Arius
   *@function tel validate
   *
   *
   */
    public function handle($request, Closure $next)
    {   
	$token = JWTAuth::getToken();
        $user = JWTAuth::toUser($token);
        $name = $user['name'];
        //save userphone in Redis
        $userphone = $user['tel'];
        if(is_null($userphone)) return $this->returnMsg('500','userPhone is null');
        /*
         此处验证订单是否重复提交
         */
         $checkredis = Redis::exists('usecar:'.$userphone);
         $check_order_mysql = OrderRecord::where('userphone','=',$userphone)->where('isAccept','=',3)->first();
         $check_deli_mysql = DeliveryRecord::where('userphone',$userphone)->where('isAccept','3')->first();
         if($checkredis)//若redis有数据则说明有订单正在进行
         {   
                //Log::info('check orderPush 1st if');
                 $result = Redis::hgetall('usecar:'.$userphone);
                 return $this->returnMsg('50066','Last order has not finished',$result);
         }   
         else if($check_order_mysql)//若数据库有数据则说明上一个订单未付款
         {   
        //      Log::info('check orderPush 2nd if');
                 $result = OrderRecord::where('userphone',$usephone)->where('isAccept','3')->first();
                 return $this->returnMsg('50088','Last order has not paid',$result);
         }else if($check_deli_mysql){
                //Log::info('check orderPush 3rd if');
                return $this->returnMsg('50088','Last send order has not paid',$check_deli_mysql);
        }   

	return $next($request);
	}
}
